//
//  DLKLineView.m
//  delongzhitou
//
//  Created by Mr.Wang on 2018/12/5.
//  Copyright © 2018 delongzhitou. All rights reserved.
//

#import "DLKLineView.h"

@interface DLKLineView()

@property (nonatomic, strong) NSMutableArray *yValues;

@property (nonatomic, strong) UILabel *noticeLabel;

@end


@implementation DLKLineView

- (void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    CGPoint point = [[touches anyObject] locationInView:self];
    
    if (point.x > kScreenWidth / 2) {
        
        [self.noticeLabel resetX:kMachineChartsChartLeftMargin];
    } else {
        [self.noticeLabel resetX:self.width *2 /3 - kMachineChartsChartLeftMargin];
    }
}


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self layoutSubControls];
        
        self.backgroundColor = kDLMachineTableAndCellBgColor;
        self.backgroundColor = [UIColor whiteColor];
        
        
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(17, 17)];
        
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = maskPath.bounds;
        maskLayer.path = maskPath.CGPath;
        self.layer.mask  = maskLayer;
        
    }
    return self;
}

- (void) chartValueSelected:(ChartViewBase *)chartView entry:(ChartDataEntry *)entry highlight:(ChartHighlight *)highlight {
    
    NSInteger index = entry.x;
    NSDictionary *dic = self.dataSourceDic[@"data"];
    NSArray *kDataArray = [NSArray arrayWithArray:dic[@"kData"]];
    NSDictionary *diccc = kDataArray[index];
    
    self.noticeLabel.hidden = NO;
    
    self.noticeLabel.text = [NSString stringWithFormat:@"最高:%@\n最低:%@\n开盘:%@\n收盘:%@\n交易量:%@\n日期:%@", diccc[@"high"], diccc[@"low"], diccc[@"open"], diccc[@"close"], diccc[@"volume"], diccc[@"date"]];
}

- (void)chartTranslated:(ChartViewBase * _Nonnull)chartView dX:(CGFloat)dX dY:(CGFloat)dY {
    NSLog(@"图表被移动");
//    NSLog(@"%f--%f", dX, dY);
    CGAffineTransform srcMatrix = chartView.viewPortHandler.touchMatrix;
    NSLog(@"%@", NSStringFromCGAffineTransform(srcMatrix));
}
- (void)chartScaled:(ChartViewBase * _Nonnull)chartView scaleX:(CGFloat)scaleX scaleY:(CGFloat)scaleY {
    
    ChartViewPortHandler *scalexxxxX = self.candleStickView.viewPortHandler;
    NSLog(@"缩放了%.2f倍", scalexxxxX.scaleX);
}

- (void) setDataSourceDic:(NSDictionary *)dataSourceDic {
    _dataSourceDic = dataSourceDic;
//    NSLog(@"k线图的数据源是：%@", dataSourceDic);
    NSDictionary *dic = dataSourceDic[@"data"];
    
    self.titleLabel.text = [NSString stringWithFormat:@"%@", dic[@"pTitle"]];
    
    NSArray *kDataArray = [NSArray arrayWithArray:dic[@"kData"]];
    if (kDataArray.count > 0) {
        //横轴数据
        NSMutableArray *xValues = [NSMutableArray array];
        
        for (NSInteger i = 0; i < kDataArray.count; i++) {
            
            NSDictionary *dic = kDataArray[i];
            NSString *dateStr = [NSString stringWithFormat:@"%@", dic[@"date"]];
            [xValues addObject:dateStr];
        }
        
        self.candleStickView.xAxis.valueFormatter = [[ChartIndexAxisValueFormatter alloc] initWithValues:xValues];
        
        
        
        // 初始化CandleChartDataEntry数组
        NSMutableArray *yValues = [NSMutableArray array];
        self.yValues = yValues;
        for (NSInteger i = 0; i < kDataArray.count; i++) {
            
            NSDictionary *dic = kDataArray[i];
            NSString *highStr = [NSString stringWithFormat:@"%@", dic[@"high"]];
            NSString *lowStr = [NSString stringWithFormat:@"%@", dic[@"low"]];
            NSString *openStr = [NSString stringWithFormat:@"%@", dic[@"open"]];
            NSString *closeStr = [NSString stringWithFormat:@"%@", dic[@"close"]];
//            NSString *volumeStr = [NSString stringWithFormat:@"%@", dic[@"volume"]];
            
            CandleChartDataEntry *y = [[CandleChartDataEntry alloc] initWithX:i shadowH:highStr.floatValue shadowL:lowStr.floatValue open:openStr.floatValue close:closeStr.floatValue];
            
            [yValues addObject:y];
        }
        
        
        CandleChartDataSet *set1 = [[CandleChartDataSet alloc] initWithValues:yValues label:@"data set"];
        set1.axisDependency = AxisDependencyLeft;
        [set1 setColor:[UIColor blueColor]];
        
        //这是用于显示最高最低值区间的立线
        set1.shadowColor = [UIColor whiteColor];
        
        //不在面板上直接显示数值
        set1.drawValuesEnabled = NO;
        // 立线的宽度
        set1.shadowWidth =0.7;
        set1.shadowColorSameAsCandle = YES;
        
        //open > close
        set1.increasingColor = [UIColor redColor];
        
        //open == close
        set1.neutralColor = [UIColor whiteColor];
        set1.neutralColor = kDLNormalBlackColor;
        
        //open < close
        set1.decreasingColor = [UIColor greenColor];
        
        //open < close是否充满颜色
        set1.decreasingFilled = YES;
        //open > close是否充满颜色
        set1.increasingFilled = YES;
        
        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
        formatter.numberStyle = kCFNumberFormatterDecimalStyle;
        set1.valueFormatter = [[ChartDefaultValueFormatter alloc] initWithFormatter:formatter];
        
        //赋值数据
        CandleChartData *data = [[CandleChartData alloc] initWithDataSet:set1];
        
        
        
        self.candleStickView.data = data;
        
        
        
    }
    
}
- (void) layoutSubControls {
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.frame = CGRectMake(kMachineChartsChartLeftMargin, 10, self.width - kMachineChartsChartLeftMargin *2, 20);
    titleLabel.textColor = kDLNormalBlackColor;
    titleLabel.font = kBoldFont(14);
    titleLabel.textAlignment = NSTextAlignmentLeft;
    titleLabel.backgroundColor = [UIColor whiteColor];
    [self addSubview:titleLabel];
    self.titleLabel = titleLabel;
    
    CandleStickChartView *candleStickView = [[CandleStickChartView alloc] initWithFrame:CGRectMake(kMachineChartsChartLeftMargin, 0, self.width - kMachineChartsChartLeftMargin *2, kMachineChartsHeight - 40)];
    [candleStickView setExtraOffsetsWithLeft:0 top:40 right:0 bottom:0];
    [self addSubview:candleStickView];
    self.candleStickView = candleStickView;
    
    ChartViewPortHandler *scaleX = self.candleStickView.viewPortHandler;
    [scaleX setMinimumScaleX:1.0];
    [scaleX setMaximumScaleX:23.5];
    
    //如果需要显示选中图表位置进行数据展示 需要设置代理 可选项
    candleStickView.delegate = self;
    candleStickView.backgroundColor = kDLMachineTableAndCellBgColor;
    candleStickView.backgroundColor = [UIColor whiteColor];
    
    //取消双击缩放
    candleStickView.doubleTapToZoomEnabled = NO;
    //画板以及边框颜色
    candleStickView.gridBackgroundColor = [UIColor purpleColor];
    candleStickView.borderColor = [UIColor yellowColor];
    
    candleStickView.pinchZoomEnabled = NO;
    //根据需要显示或隐藏边框以及画板
    candleStickView.drawGridBackgroundEnabled = NO;
    candleStickView.drawBordersEnabled = NO;
    candleStickView.maxVisibleCount = 10;
    candleStickView.legend.enabled = NO;
    candleStickView.scaleYEnabled = NO;
    
    [candleStickView animateWithYAxisDuration:0.5];
//    [candleStickView animateWithXAxisDuration:0.5];
    
    //设置X轴相关参数
    ChartXAxis *xAxis = candleStickView.xAxis;
    xAxis.labelPosition = XAxisLabelPositionBottom;
    xAxis.drawGridLinesEnabled = NO;
    //    xAxis.granularityEnabled = YES;
    xAxis.labelCount = 4;
    xAxis.forceLabelsEnabled = NO;
    xAxis.labelTextColor = kDLNormalBlackColor;
    xAxis.axisLineWidth = 0.5;
    xAxis.axisLineColor = [UIColor grayColor];
    
    //    xAxis.gridColor = [UIColor grayColor];
    //    xAxis.drawAxisLineEnabled = YES;
    //    xAxis.forceLabelsEnabled = NO;
    //    xAxis.axisLineWidth = 0.5;
    //    xAxis.axisLineColor = [UIColor grayColor];
    
    
    //设置y轴相关参数 将坐标轴显示在左边
    ChartYAxis *leftAxis = candleStickView.leftAxis;
    leftAxis.labelCount = 6;
    leftAxis.drawGridLinesEnabled = YES;
    leftAxis.axisLineWidth = 0.5;
    leftAxis.axisLineColor = [UIColor grayColor];
    leftAxis.labelPosition = YAxisLabelPositionOutsideChart;
    leftAxis.labelTextColor = kDLNormalBlackColor;
    leftAxis.labelFont = kSystemFont(12);
    
//    leftAxis.inverted = NO;
//    leftAxis.zeroLineWidth = 0.5;
//    leftAxis.drawZeroLineEnabled = YES;
//    leftAxis.gridColor = [UIColor grayColor];
    
    
    leftAxis.drawAxisLineEnabled = YES;
    ChartYAxis *rightAxis = candleStickView.rightAxis;
    rightAxis.enabled = NO;
    
    [self bringSubviewToFront:titleLabel];
    
    UILabel *noticeLabel = [UILabel new];
    noticeLabel.frame = CGRectMake(self.width *2 /3 - kMachineChartsChartLeftMargin, 13, self.width / 3, kMachineChartsHeight *2 /5);
    noticeLabel.textColor = kDLNormalBlackColor;
    noticeLabel.textColor = [UIColor whiteColor];
    noticeLabel.backgroundColor = kColorRGBA(100, 100, 100, 0.7);
    noticeLabel.textAlignment = NSTextAlignmentLeft;
    noticeLabel.font = kSystemFont(14);
    noticeLabel.numberOfLines = 0;
    noticeLabel.lineBreakMode = NSLineBreakByCharWrapping;
    [self addSubview:noticeLabel];
    self.noticeLabel = noticeLabel;
    noticeLabel.hidden = YES;
    
    //设置y轴0.xx的时候显示0.xx而不是.xx
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setPositiveFormat:@"#0.00"];
    self.candleStickView.leftAxis.valueFormatter = [[ChartDefaultAxisValueFormatter alloc] initWithFormatter:formatter];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
